//
//  KLMapView.m
//  KiklinkApp
//
//  Created by LF on 14/11/2.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "KLMapView.h"
#import "BMKAnnotation.h"

const double DEFAULT_REGION_DELTA = 0.01;


@interface KLMapView ()
{
    BOOL isInited;
    double mLongitude;
    double mLatitude;
    BOOL isPined;
    NSString *mWord;
    double mRegion;
}
@end


@implementation KLMapView

- (void)onViewDidAppear
{
    self.bdMapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [self addSubview:self.bdMapView];
    
    [self.bdMapView viewWillAppear];
    self.bdMapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    self.userInteractionEnabled = NO;
    
    if(isInited)
    {
        if(isPined)
        {
            [self setPinWithWord:mWord longitude:mLongitude latitude:mLatitude region:mRegion];
        }
        else
        {
            [self setDisplayWithLongitude:mLongitude latitude:mLatitude region:mRegion];
        }
    }
}

- (void)onViewWillDisappear
{
    if(self.bdMapView != nil)
    {
        [self.bdMapView viewWillDisappear];
        self.bdMapView.delegate = nil; // 不用时，置nil
    }
}

- (void)layoutSubviews
{
    [self onViewDidAppear];
    [super layoutSubviews];
}

//设定内容----------------------------------------------------------

- (void)setDisplayWithLongitude:(double)longitude latitude:(double)latitude
{
    [self setDisplayWithLongitude:longitude latitude:latitude region:DEFAULT_REGION_DELTA];
}

- (void)setDisplayWithLongitude:(double)longitude latitude:(double)latitude region:(double)region
{
    if(region == 0)
    {
        region = DEFAULT_REGION_DELTA;
    }
    
    isInited = YES;
    mLongitude = longitude;
    mLatitude = latitude;
    mRegion = region;
    
    //注意此处参数的顺序反过来了
    CLLocationCoordinate2D target = CLLocationCoordinate2DMake(latitude, longitude);
    BMKCoordinateRegion regionObj = {target, {region, region}};
    [self.bdMapView setRegion:regionObj animated:YES];
}

- (void)setPinWithWord:(NSString*)word longitude:(double)longitude latitude:(double)latitude
{
    [self setPinWithWord:word longitude:longitude latitude:latitude region:DEFAULT_REGION_DELTA];
}

- (void)setPinWithWord:(NSString*)word longitude:(double)longitude latitude:(double)latitude region:(double)region
{
    if(region == 0)
    {
        region = DEFAULT_REGION_DELTA;
    }
    
    [self setDisplayWithLongitude:longitude latitude:latitude region:region];
    
    isPined = YES;
    mWord = word;
    
    //注意此处参数的顺序反过来了
    CLLocationCoordinate2D target = CLLocationCoordinate2DMake(latitude, longitude);
    BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
    annotation.coordinate = target;
    annotation.title = word;
    [self.bdMapView addAnnotation:annotation];
}



@end
